package com.example.weatherforecast.weatherdatatool;

import java.io.IOException;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：coderChen
 * @Package：com.example.weatherforecast.tool
 * @Project：WeatherForecast
 * @Date：2024/1/1 16:47
 * @Filename：WeatherApi
 */

public class WeatherApi {

    private static final String TAG = WeatherApi.class.getSimpleName();

    public static CurrentWeatherInfo getWeatherData(String url) {
        CurrentWeatherInfo currentWeatherInfo;

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        try {
            URL requestUrl = new URL(url);
            urlConnection = (HttpURLConnection) requestUrl.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder buffer = new StringBuilder();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append("\n");
            }

            if (buffer.length() == 0) {
                return null;
            }
            // 解析 JSON 数据
            String jsonResponse = buffer.toString();
            Log.d(TAG, "JSON Response: " + jsonResponse); // 添加日志输出
            JSONObject jsonObject = new JSONObject(jsonResponse);
            JSONObject cityInfo = jsonObject.getJSONObject("cityInfo");
            // 提取城市信息
            String cityName = cityInfo.getString("city");
            String updateTime = cityInfo.getString("updateTime");

            // 提取天气数据
            JSONObject data = jsonObject.getJSONObject("data");
            String temperature = data.getString("wendu");

            // 提取最低温度、最高温度和天气类型
            JSONArray forecastArray = data.getJSONArray("forecast");
            JSONObject todayForecast = forecastArray.getJSONObject(0); // 获取第一天的天气预报
            String lowestTemperature = WeatherDataParser.parseTemperature(todayForecast.getString("low"));
            String highestTemperature = WeatherDataParser.parseTemperature(todayForecast.getString("high"));
            String weatherType = todayForecast.getString("type");
            String notice = todayForecast.getString("notice");
            String airQuality = data.getString("quality");

            List<RecentWeatherInfo> forecasts = new ArrayList<>();
            int numDays = Math.min(forecastArray.length(), 12); //设定循环次数，获取近日多少天内的天气信息
            for (int i = 1; i < numDays; i++) {
                JSONObject forecastObject = forecastArray.getJSONObject(i);
                String date = WeatherDataParser.parseDate(forecastObject.getString("ymd"));
                String week = forecastObject.getString("week");
                String type = forecastObject.getString("type");
                String lowTemperature = WeatherDataParser.parseTemperature(forecastObject.getString("low"));
                String highTemperature = WeatherDataParser.parseTemperature(forecastObject.getString("high"));

                String Temperature = lowTemperature + " ~ " + highTemperature;

                RecentWeatherInfo forecast = new RecentWeatherInfo(date, week, type, Temperature);
                forecasts.add(forecast);
            }

            // 创建 WeatherInfo 对象
            currentWeatherInfo = new CurrentWeatherInfo(cityName, temperature, lowestTemperature, highestTemperature, weatherType, airQuality,forecasts,updateTime,notice);
        } catch (IOException | JSONException e) {
            Log.e(TAG, "Error fetching weather data", e);
//            return getDefaultWeatherInfo();
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
        return currentWeatherInfo;
    }
}


